<?php
namespace app\api\model;
use app\api\controller\Aes;
use think\Db;

class CreditModel extends BaseModel
{
	protected $table = "xst_user";
    protected $rule = [
        'id' => '',
    ];
    protected $msg = [
        'id' => '',
    ];
	//首页信用显示
	public function getOneId($id)
    {
        return $this->where('id',$id)->find();
    }
	/*/实名认证
	public function reals($id,$name,$card,$phone,$cost)
    {
       return $this->where('id',$id)->update([
            'name'=>$name,
			'card'=>$card,
			'card'=>$card,
			'phone'=>$phone,
            'cost'=>$cost
        ]);
    }*/
   //我的资产
   public function balance($id)
    {
        return Db::name('balance')->where('uid',$id)->find();
    }
	//流通币流通详情
	public function circulate($id)
    {
         return Db::name('balance_log')->where('uid',$id)->where('balance_type',1)->select();
    }
	//个人资料
	public function Personal ($id){
		 return $this->where('id',$id)->find();
	}
	//个人资料修改昵称
	public function nickname($id,$nickname){
		 return $this->where('id',$id)->update([
            'nickname'=>$nickname
        ]);
	}
  	
    //个人资料解绑手机号
    public function relieve($uid,$phone){
        return $this->where('id',$uid)->where('phone',$phone)->update([
            'phone'=>''
        ]);
    }
	//个人资料修改性别
	public function sex($id,$sex){
		 return $this->where('id',$id)->update([
            'sex'=>$sex
        ]);
	}
	//个人资料修改生日
	public function birthday($id,$birthday){
		 return $this->where('id',$id)->update([
            'birthday'=>$birthday
        ]);
	}
	//个人资料修改地区
	public function area($id,$area){
		 return $this->where('id',$id)->update([
            'area'=>$area
        ]);
	}
	//个人资料修改地区
	public function Picture($id,$Picture){
		 return $this->where('id',$id)->update([
            'Picture'=>$Picture
        ]);
	}
	//添加头像
	public function upload($file){//上传图片
		$fileName = md5(time());
            $fileRoute = ROOT_PATH . '/upload/Picture/';
            // 创建文件夹
            if (!file_exists($fileRoute)) {
                mkdir($fileRoute);
            }
            $info = $file->move($fileRoute, $fileName);
            if ($info) {
                // 缩略图
                $photo = '/upload/Picture/'.$info->getFilename();

            } else {
                // 上传失败获取错误信息
                return $file->getError();
            }
        return $photo;
	}
    //钱包地址
    public function wallet($uid)
    {
        $data = $this
            ->where('id',$uid)
            ->find();
        //AES加密
        $plainText =$data['phone'];
        $aes = new Aes();
        $keyStr = '1e8iFvuH37UeIToQBZLxVrlP181p52vK';
        $aes->set_key($keyStr);
        $aes->require_pkcs5();
        $money_address = $aes->encrypt($plainText);
        $data['wallet_adress']=$money_address;
        return $data;
    }
    //转账
    public function transsfer($uid)
    {
        $data = $_POST;
        $balanceModel = new BalanceModel();
        $Xst = new XstModel();
        $balance =  $balanceModel
            ->where('uid',$uid)
            ->find();
     	
        //获取用户信息
        $user_info = $this->where('id',$uid)->find();
        //检测用户余额是否充足
        if(abs($data['number'])>$balance["circulate"])
        {
            return '10004';
        }
        $to_address = $data['wallet_address'];
        //判断对方地址是否是自己
        if($user_info['xst_address'] == $to_address){
            return '20001';
        }
        //判断支付密码
        if(authcode($user_info['pay_pwd'],'DECODE')!=$data['wallet_password'])
        {
            return '10000';
        }
        //获取对方信息
        $user_info_to = $this->where('xst_address',$to_address)->whereOr('shop_address',$to_address)->find();
        if(empty($user_info_to)){
            return '20002';
        }
        /*$eth_yue = $Xst->getbalance($user_info['xst_address']);
        if($eth_yue < ($data['number'] * 0.00000006)){
            return '20003';
        }*/
      //die;
        //转账
       $balance_info =  $balanceModel
            ->where('uid',$user_info_to['id'])
            ->find();
        Db::startTrans();
        $r = array();
        //自己减
        $r [] = changeBalance($uid,"circulate",0,$data['number'],2,"转出xst",1);
        if($user_info_to['xst_address'] == $to_address){
            //对方加
             $xst_ft = 0;
            if($data['number'] > $balance_info['circulation']){
                $circulation = floor($balance_info['circulation'] / 100);
                $xst_ft = $data['number'] + $circulation*100;
                //$r [] = $balance->where("uid",$uid)->setDec("circulate",$num);
                $r [] = $balance->where("uid",$uid)->setDec("circulation",$circulation*100);
            }else{
                $xst_ft = $data['number'] *2;
                //$r [] = $balance->where("uid",$uid)->setDec("circulate",$num);
                $r [] = $balance->where("uid",$uid)->setDec("circulation",$data['number']);
            }
            $r [] = changeBalance($user_info_to['id'],'frozen',1,$xst_ft*2,1,"转入冻结xst",4);
            $r []  = direct($user_info_to['id']);
            //转账
            //$res = $Xst->transfer($user_info['xst_address'],$privateKeys=$user_info['xst_key'],$data['number'],$to_address,$uid);
            $res = 1;
            $r[] = release($user_info_to['id'],'',$xst_ft*2,$xst_ft,2);
        }elseif($user_info_to['shop_address'] == $to_address){
        	 //对方加
            $r [] = changeBalance($user_info_to['id'],'shop_xst',1,$data['number']*0.85,1,"转入商户xst",5);
        }
      	$r [] = accelerate($user_info_to['id'],$data['number'],$uid);
      	/*if($res['code'] == 1){
            $r [] = true;
        }else{
            $r [] = false;
        }*/
        if(!in_array(false,$r,true))
        {
            Db::commit();
            return '10001';
        }else{
            Db::rollback();
            return '10002';
        }
    }
    //推荐关系图
     public function recommend($uid,$phone)
    {
        $where=[];
        if($phone)
        {
            $where['phone'] = $phone;
        }
        $userInfo=$this->where('id',$uid)->find();
        $where['pid'] = $userInfo["id"];
        $data=$this->where($where)->select();
        foreach ($data as $key=>$val)
        {
            $phone = substr($val['phone'],0,3);
            $phones = substr($val['phone'],-4,4);
            $data[$key]['phone']=$phone.'****'.$phones;
        }
        return $data;
    }
  //eth兑换xst
    public function exchange_xst($uid){
        $num = abs(input("num"));
        $pwd = input("pwd");
        $user_info = $this->getInfo(array("id"=>$uid));
        $balanceModel = new BalanceModel();
        $balance = $balanceModel->where('uid',$uid)->find();
        if($num  <= 0 ){
            AjaxReturn("-1","您输入的数量有误");
        }
        if($balance['eth'] < $num){
            AjaxReturn("-2","您的余额不足");
        }
        if(authcode($user_info['pay_pwd'],"DECODE") != $pwd){
            AjaxReturn("-3","您的支付密码错误");
        }
        $r = array();
        //获取eth 价格
        $setting = new SettingModel();
        $price = $setting->where("id",7)->find();
        //冻结币
        $ltb = $num*$price['value'];
        $from_info = $this->where("id",2)->find();
        $this->startTrans();
        $Xst = new XstModel();
        //转账eth
        $from = $user_info['xst_address'];
        $to = $from_info['xst_address'];
        $value = $num;
        $privateKeys = $user_info['xst_key'];
        $r [] = $Xst->sendTransaction($from,$to,$value,$privateKeys,$uid);
        //转账xst
        //$res = $Xst->transfer($from=$from_info['xst_address'],$privateKeys=$from_info['xst_key'],$num*$price['value']*2,$user_info['xst_address'],$uid);
      	/*$res =1;
        if($res['code'] == 1){
            $r [] = true;
        }else{
            $r [] = false;
        }*/
        //添加日志
        $r [] = changeBalance($uid,"eth",0,$num,9,"兑换xst消耗eth",3);
        $r [] = changeBalance($uid,"circulate",1,$ltb,9,"兑换xst收益流通币",1);
      	$r []  = direct($uid);
      	//$r [] = release($uid,'',$ltb,$num*$price['value'],3);
        if(in_array(false,$r)){
            $this->rollback();
            AjaxReturn("-4","兑换失败");
        } else{
            $this->commit();
            AjaxReturn("1","兑换成功");
        }
   }
    //xst兑换eth
    public function exchange_eth($uid){
        $num = abs(input("num"));
        $pwd = input("pwd");
        $user_info = $this->getInfo(array("id"=>$uid));
        $balanceModel = new BalanceModel();
        $balance = $balanceModel->where('uid',$uid)->find();
        if($num  <= 0 ){
            AjaxReturn("-1","您输入的数量有误");
        }
        if($balance['circulate'] < $num){
            AjaxReturn("-2","您的余额不足");
        }
        if(authcode($user_info['pay_pwd'],"DECODE") != $pwd){
            AjaxReturn("-3","您的支付密码错误");
        }
        $r = array();
        $from_info = $this->where("id",2)->find();
        //流通币
        //获取eth 价格
        $setting = new SettingModel();
        $price = $setting->where("id",7)->find();
        $ltb = round($num/$price['value'],4);
        $this->startTrans();
        $Xst = new XstModel();
        //转账eth
        $from = $from_info['xst_address'];
        $to = $user_info['xst_address'];
        $value = $num;
        $privateKeys = $from_info['xst_key'];
        $r [] = $Xst->sendTransaction($from,$to,$ltb,$privateKeys,$uid);
    //  dump($r);die;
        //转账xst
       // $res = $Xst->transfer($user_info['xst_address'],$privateKeys=$user_info['xst_key'],$value,$from_info['xst_address'],$uid);
      	/*$res =1;
        
      	if($res['code'] == 1){
            $r [] = true;
        }else{
            $this->rollback();
            AjaxReturn("-4",$res['message']);
        }*/
        //添加日志
        $r [] = changeBalance($uid,"eth",1,$ltb,9,"兑换eth消耗xst",3);
        $r [] = changeBalance($uid,"circulate",0,$num,9,"兑换eth消耗流通币",1);
        if(in_array(false,$r)){
            $this->rollback();
            AjaxReturn("-4","兑换失败");
        } else{
            $this->commit();
            AjaxReturn("1","兑换成功");
        }
    }
  	//提币
    public function withdrawal_eth($uid){
        $user_info = $this->getInfo(array("id"=>$uid));
        //地址
        $address = input("address");
        //数量
        $num = input("num");
        //密码
        $pwd = input("pay_pwd");
        $address_info = $this->getInfo(array("xst_address"=>$address));
        if(!empty($address_info)){
            AjaxReturn("-1","地址输入有误");
        }
        if($address == $user_info['xst_address']){
            AjaxReturn("-1","地址输入有误");
        }
        if(abs($num) < 0){
            AjaxReturn("-2","您输入的数量有误");
        }
        if($pwd != authcode($user_info['pay_pwd'],"DECODE")){
            AjaxReturn("-3","您的支付密码输入不正确");
        }
        $balance = new BalanceModel();
        $balance_info = $balance->getInfo(array("uid"=>$uid));
        $xst = new XstModel();
       // $eth_yue = $xst->getbalance($address);
        if($num > $balance_info['eth']){
            AjaxReturn("-4","您钱包里的ETH不足");
        }
        $this->startTrans();
        $r = array();
        $r [] = $xst->sendTransaction($user_info['xst_address'],$address,$num,$user_info['xst_key'],$uid);
        $r [] = changeBalance($user_info['id'],"eth",0,$num,3,"提币eth",3);
        if(in_array(false,$r)){
            $this->rollback();
            jaxReturn("0","提币失败");
        }else{
            $this->commit();
            AjaxReturn("1","提币成功");
        }
    }
  //复投
    public function double_throw($uid)
    {
        $user_info = $this->getInfo(array("id" => $uid));
        $num          = abs(input("num"));
        $pwd          = input("pwd");
        $balance      = new BalanceModel();
        $balance_info = $balance->getInfo(array("uid" => $uid));
        if (($balance_info['circulate'] + $balance_info['shop_xst']) < $num) {
            AjaxReturn("-1", "您的流通币不足");
        }
        if (($num % 100) != 0) {
            AjaxReturn("-2", "请输入100的倍数");
        }
        if ($pwd != authcode($user_info['pay_pwd'], "DECODE")) {
            AjaxReturn("-3", "您的支付密码输入不正确");
        }
        $this->startTrans();
        $r = array();
      	if($balance_info['circulate'] > $num){
        	$r [] = $balance->where("uid",$uid)->setDec("circulate",$num);
        }elseif($balance_info['circulate'] < $num){
          	$circulation = floor($balance_info['circulate'] / 100);
          	$sheng_num = $num-$circulation*100;
        	$r [] = $balance->where("uid",$uid)->setDec("circulate",$circulation*100);
          	$r [] = $balance->where("uid",$uid)->setDec("shop_xst",$sheng_num);
        }
        $xst_ft = 0;
        if($num > $balance_info['circulation']){
         	$circulation = floor($balance_info['circulation'] / 100);
            $xst_ft = $num + $circulation*100;
            $r [] = $balance->where("uid",$uid)->setDec("circulation",$circulation*100);
        }else{
            $xst_ft = $num *2;
            $r [] = $balance->where("uid",$uid)->setDec("circulation",$num);
        }
        $r [] = release($uid,0,$xst_ft*2,$xst_ft,4);
      	$r [] = changeBalance($uid,'frozen',1,$xst_ft*2,1,"转入冻结xst",4);
      	$r [] = accelerate($uid,$num);
        if(in_array(false,$r,true)){
            $this->rollback();
            AjaxReturn("0", "复投失败");
        }else{
            $this->commit();
            AjaxReturn("1", "复投成功");
        }
    }
    //领取红包
    public function Get_a_red_envelope($uid)
    {
        $balance      = new BalanceModel();
        $balance_info = $balance->getInfo(array("uid" => $uid));
        $info_today = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("status",1)->find();
        if(!empty($info_today)){
            AjaxReturn("1", "今日已领取过");
        }
        $info_yesterday = Db::name('red_packet')->whereTime('createtime', 'yesterday')->where("uid",$uid)->where("status",1)->order("receivetime desc")->find();
        $this->startTrans();
        $r = array();
        if($info_yesterday){
            //流通币
            $ltb_sum = Db::name('red_packet')->where('id>'.$info_yesterday['id'])->where("uid",$uid)->where("type",1)->sum('num');
            //循环币
            $xhb_sum = Db::name('red_packet')->where('id>'.$info_yesterday['id'])->where("uid",$uid)->where("type",2)->sum('num');
            $r[] = Db::name("red_packet")->where('id>',$info_yesterday['id'])->where("uid",$uid)->update(array('status'=>1));
        }else{
            //流通币
            $ltb_sum = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("uid",$uid)->where("type",1)->sum('num');
            //循环币
            $xhb_sum = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("type",2)->sum('num');
            $r[] = Db::name("red_packet")->whereTime('createtime', 'today')->where("uid",$uid)->update(array('status'=>1));
        }
       	$array_ltb = array();
        $array_ltb ['uid'] = $uid;
        $array_ltb ['type'] = 1;
        $array_ltb ['num'] = $ltb_sum;
        $array_ltb ['create_time'] = time();
        $r [] = Db::name("red_packet_log")->where("uid",$uid)->insert($array_ltb);
        $array_xhb = array();
        $array_xhb ['uid'] = $uid;
        $array_xhb ['type'] = 2;
        $array_xhb ['num'] = $xhb_sum;
        $array_xhb ['create_time'] = time();
        $r [] = Db::name("red_packet_log")->where("uid",$uid)->insert($array_xhb);
        $r [] = $balance->where("uid",$uid)->setInc("circulate",$ltb_sum);
        $r [] = $balance->where("uid",$uid)->setInc("circulation",$xhb_sum);
      	$r [] = changeBalance($uid,'frozen',0,$xhb_sum + $ltb_sum,1,"领取红包消耗冻结xst",4);
        if(in_array(false,$r)){
            $this->rollback();
            AjaxReturn("0", "领取失败");
        }else{
            $this->commit();
            AjaxReturn("1", "领取成功");
        }
    }
  public function is_get_redenvelope($uid)
    {
        $info_today = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("status",1)->find();
        $is_get = true;
        if($info_today){
            $is_get = false;
        }
        $info_yesterday = Db::name('red_packet')->whereTime('createtime', 'yesterday')->where("uid",$uid)->where("status",1)->order("receivetime desc")->find();
    	if($info_yesterday){
            //流通币
            $ltb_sum = Db::name('red_packet')->where('id>'.$info_yesterday['id'])->where("uid",$uid)->where("type",1)->sum('num');
            //循环币
            $xhb_sum = Db::name('red_packet')->where('id>'.$info_yesterday['id'])->where("uid",$uid)->where("type",2)->sum('num');
         
        }else{
            //流通币
            $ltb_sum = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("type",1)->sum('num');
            //循环币
            $xhb_sum = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("type",2)->sum('num');
        }
        $data = [
            'is_get' => $is_get,
            'ltb' => $ltb_sum,
            'xhb' => $xhb_sum
        ];
        AjaxReturn("1", "成功",$data);
    }
  public function redenvelope_log($uid)
    {
        $list =  Db::name('red_packet_log')->where("uid",$uid)->order("create_time desc")->select();
        foreach ($list as $k=>$v){
          	$list[$k]['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
            if($v['type'] == 1){
                $list[$k]['type'] = "流通币";
            }else{
                $list[$k]['type'] = "循环币";
            }
        }
        $balance      = new BalanceModel();
        $balance_info = $balance->getInfo(array("uid" => $uid));
    	$res = $this->getredenvelope($uid);
        $data['red'] = $res;
        $data['log'] = $list;
        $data['xst'] = $balance_info['circulate'];
        AjaxReturn("1", "成功",$data);
    }
  public function getredenvelope($uid){
        $info_today = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("status",1)->find();
        $is_get = true;
        if($info_today){
            $is_get = false;
        }
        $info_yesterday = Db::name('red_packet')->whereTime('createtime', 'yesterday')->where("uid",$uid)->where("status",1)->order("receivetime desc")->find();
        if($info_yesterday){
            //流通币
            $ltb_sum = Db::name('red_packet')->where('id>'.$info_yesterday['id'])->where("uid",$uid)->where("type",1)->sum('num');
            //循环币
            $xhb_sum = Db::name('red_packet')->where('id>'.$info_yesterday['id'])->where("uid",$uid)->where("type",2)->sum('num');
        }else{
            //流通币
            $ltb_sum = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("type",1)->sum('num');
            //循环币
            $xhb_sum = Db::name('red_packet')->whereTime('createtime', 'today')->where("uid",$uid)->where("type",2)->sum('num');
        }
        $data = [
            'is_get' => $is_get,
            'ltb' => $ltb_sum,
            'xhb' => $xhb_sum
        ];
        return $data;
    }
}
	
?>